{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Uncertainty calculation for model: SD2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites, images and settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "#definet the color pallette\n",
    "vibgYOR = ['330044', '220066', '1133cc', '33dd00', 'ffda21', 'ff6622', 'd10000']\n",
    "compositeImage =ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\");\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)\n",
    "# generete the pixel area map\n",
    "pixelArea = ee.Image.pixelArea().divide(10000) # to ha unit\n",
    "# load the biome layer\n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "biomeMask = biomeLayer.mask(biomeLayer.neq(98)).mask(biomeLayer.neq(99)).gt(0)\n",
    "# load the mean maps for present and potential\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the biomass density layers\n",
    "mergedAGB_PresentMean =  ee.Image(\"users/leonidmoore/ForestBiomass/RemoteSensingModel/ESA_CCI_AGB_Map_bias_corrected_1km_2010\").unmask().multiply(carbonConcentration) \n",
    "mergedAGB_PotentialMean = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_SD2_Potential_density_Ensambled_Mean\").unmask()\n",
    "# define the standardized projection\n",
    "stdProj = mergedAGB_PresentMean.projection()\n",
    "# load the two forest cover layer for existing and potential forest\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask()# make sure it's in  0-1 scale\n",
    "potentialForestCover = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask() # make sure it's in  0-1 scale\n",
    "\n",
    "# define the present and potential forest cover masks\n",
    "presentMask = presentForestCover.gt(0)\n",
    "potentialMask = potentialForestCover.gt(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Calculate the present and potential AGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the difference of the two density maps\n",
    "potentialHigher = mergedAGB_PotentialMean.multiply(pixelArea).subtract(mergedAGB_PresentMean.multiply(pixelArea)).gte(0)\n",
    "potentialLower = mergedAGB_PotentialMean.multiply(pixelArea).subtract(mergedAGB_PresentMean.multiply(pixelArea)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "potentialAGB_Density = mergedAGB_PresentMean.multiply(potentialLower).add(mergedAGB_PotentialMean.multiply(potentialHigher))\n",
    "presentAGB_Density = mergedAGB_PresentMean\n",
    "# get the abs of present and potential AGB\n",
    "presentAGB_Abs = presentAGB_Density.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "potentialAGB_Abs = potentialAGB_Density.multiply(pixelArea).multiply(potentialMask).divide(1000000000)\n",
    "\n",
    "# presentAGB_Abs_Sum = presentAGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                  geometry = unboundedGeo,\n",
    "#                                                  crs = 'EPSG:4326',\n",
    "#                                                  crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                  maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB:', 'blue', attrs=['bold']),presentAGB_Abs_Sum.getInfo())\n",
    "# potentialAGB_Abs_Sum = potentialAGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                      geometry = unboundedGeo,\n",
    "#                                                      crs = 'EPSG:4326',\n",
    "#                                                      crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                      maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB:', 'blue', attrs=['bold']),potentialAGB_Abs_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Calculate the Upper and Lower of present and potential AGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present prediction lower and upper layer\n",
    "mergedPredictionInterval = ee.Image(\"users/leonidmoore/ForestBiomass/RemoteSensingModel/ESA_CCI_Biomass_Map_SD_1km_2010\").unmask().multiply(carbonConcentration)\n",
    "presentAGB_Lower1 = mergedAGB_PresentMean.subtract(mergedPredictionInterval)\n",
    "presentAGB_Lower = presentAGB_Lower1.mask(presentAGB_Lower1.gte(0)).unmask()\n",
    "presentAGB_Upper = mergedAGB_PresentMean.add(mergedPredictionInterval)\n",
    "\n",
    "# get the upper and lower layer\n",
    "mergedAGB_PotentialLower = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_SD2_Potential_density_Ensambled_Percentile\").select(['lower']).unmask() \n",
    "mergedAGB_PotentialUpper = ee.Image(\"users/nordmannmoore/ForestBiomass/RemoteSensingModel/EnsambleMaps/Predicted_SD2_Potential_density_Ensambled_Percentile\").select(['upper']).unmask() \n",
    "\n",
    "mergedAGB_PotentialLower1 = presentAGB_Lower.multiply(potentialLower).add(mergedAGB_PotentialLower.multiply(potentialHigher))\n",
    "mergedAGB_PotentialUpper1 = presentAGB_Upper.multiply(potentialLower).add(mergedAGB_PotentialUpper.multiply(potentialHigher))\n",
    "\n",
    "# define the masks to mask the present and potential lower maps\n",
    "potentialAGB_Lower_Larger = mergedAGB_PotentialLower1.subtract(presentAGB_Lower).gte(0) # potential is larger than present mean\n",
    "potentialAGB_Lower_Smaller = mergedAGB_PotentialLower1.subtract(presentAGB_Lower).lt(0)\n",
    "# define the masks to mask the present and potential upper maps\n",
    "potentialAGB_Upper_Larger = mergedAGB_PotentialUpper1.subtract(presentAGB_Upper).gte(0) # potential is larger than present upper\n",
    "potentialAGB_Upper_Smaller = mergedAGB_PotentialUpper1.subtract(presentAGB_Upper).lt(0)\n",
    "\n",
    "# replace the lower potential value by present biomass density value\n",
    "potentialAGB_AdjLower = mergedAGB_PotentialLower.multiply(potentialAGB_Lower_Larger).add(presentAGB_Lower.multiply(potentialAGB_Lower_Smaller))\n",
    "potentialAGB_AdjUpper = mergedAGB_PotentialUpper.multiply(potentialAGB_Upper_Larger).add(presentAGB_Upper.multiply(potentialAGB_Upper_Smaller))\n",
    "\n",
    "# present lower and higher\n",
    "presentAGB_Lower_Abs = presentAGB_Lower.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "presentAGB_Upper_Abs = presentAGB_Upper.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "\n",
    "# abs potential lower and higher\n",
    "potentialAGB_Lower_Abs = potentialAGB_AdjLower.multiply(pixelArea).multiply(potentialMask).divide(1000000000)\n",
    "potentialAGB_Upper_Abs = potentialAGB_AdjUpper.multiply(pixelArea).multiply(potentialMask).divide(1000000000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Calculate the present AGB lower\n",
    "# presentAGB_Lower_Sum = presentAGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                          geometry = unboundedGeo,\n",
    "#                                                          crs = 'EPSG:4326',\n",
    "#                                                          crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                          maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB Lower:', 'blue', attrs=['bold']),presentAGB_Lower_Sum.getInfo())\n",
    "\n",
    "# # Calculate the present AGB upper\n",
    "# presentAGB_Upper_Sum = presentAGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                          geometry = unboundedGeo,\n",
    "#                                                          crs = 'EPSG:4326',\n",
    "#                                                          crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                          maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB Upper:', 'blue', attrs=['bold']),presentAGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialAGB_Lower_Sum = potentialAGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                              geometry = unboundedGeo,\n",
    "#                                                              crs = 'EPSG:4326',\n",
    "#                                                              crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                              maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB Lower:', 'blue', attrs=['bold']),potentialAGB_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialAGB_Upper_Sum = potentialAGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                              geometry = unboundedGeo,\n",
    "#                                                              crs = 'EPSG:4326',\n",
    "#                                                              crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                              maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB Upper:', 'blue', attrs=['bold']),potentialAGB_Upper_Sum.getInfo())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Calculate the Upper and Lower of present and potential Root and TGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the root shoot map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "rootShootRatioLower = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_percentile_Map\").select('lower').unmask()\n",
    "rootShootRatioUpper = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_percentile_Map\").select('upper').unmask()\n",
    "# \n",
    "presentRoot_Lower_Abs = presentAGB_Lower_Abs.multiply(rootShootRatioLower).mask(presentMask)\n",
    "presentRoot_Upper_Abs = presentAGB_Upper_Abs.multiply(rootShootRatioUpper).mask(presentMask)\n",
    "\n",
    "potentialRoot_Lower_Abs = potentialAGB_Lower_Abs.multiply(rootShootRatioLower).mask(potentialMask)\n",
    "potentialRoot_Upper_Abs = potentialAGB_Upper_Abs.multiply(rootShootRatioUpper).mask(potentialMask)\n",
    "\n",
    "presentRoot_Abs = presentAGB_Abs.multiply(rootShootRatio).mask(presentMask)\n",
    "potentialRoot_Abs = potentialAGB_Abs.multiply(rootShootRatio).mask(potentialMask)\n",
    "\n",
    "presentTGB_Abs = presentAGB_Abs.multiply(rootShootRatio).add(presentAGB_Abs)#.multiply(presentMask)\n",
    "potentialTGB_Abs = potentialAGB_Abs.multiply(rootShootRatio).add(potentialAGB_Abs)#.multiply(potentialMask)\n",
    "\n",
    "presentTGB  = presentAGB_Density.multiply(rootShootRatio.add(1))\n",
    "# density \n",
    "presentRoot = presentAGB_Density.multiply(rootShootRatio)\n",
    "presentRoot_Lower = presentAGB_Lower.multiply(rootShootRatioLower)\n",
    "presentRoot_Upper = presentAGB_Upper.multiply(rootShootRatioLower)\n",
    "\n",
    "potentialRoot_Lower = potentialAGB_AdjLower.multiply(rootShootRatioLower)\n",
    "potentialRoot_Upper = potentialAGB_AdjUpper.multiply(rootShootRatioLower)\n",
    "\n",
    "presentTGB_Lower = presentAGB_Lower.multiply(rootShootRatioLower).add(presentAGB_Lower)\n",
    "presentTGB_Upper = presentAGB_Upper.multiply(rootShootRatioLower).add(presentAGB_Upper)\n",
    "\n",
    "potentialTGB_Lower = potentialAGB_AdjLower.multiply(rootShootRatioLower).add(potentialAGB_AdjLower)\n",
    "potentialTGB_Upper = potentialAGB_AdjUpper.multiply(rootShootRatioLower).add(potentialAGB_AdjUpper)\n",
    "\n",
    "# presentTGB_Abs_Sum = presentTGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                  geometry = unboundedGeo,\n",
    "#                                                  crs = 'EPSG:4326',\n",
    "#                                                  crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                  maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB:', 'blue', attrs=['bold']),presentTGB_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialTGB_Abs_Sum = potentialTGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                      geometry = unboundedGeo,\n",
    "#                                                      crs = 'EPSG:4326',\n",
    "#                                                      crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                      maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB:', 'blue', attrs=['bold']),potentialTGB_Abs_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Abs_Sum = presentRoot_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                    geometry = unboundedGeo,\n",
    "#                                                    crs = 'EPSG:4326',\n",
    "#                                                    crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                    maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots:', 'blue', attrs=['bold']),presentRoot_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialRoot_Abs_Sum = potentialRoot_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots:', 'blue', attrs=['bold']),potentialRoot_Abs_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Lower_Sum = presentRoot_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots Lower:', 'blue', attrs=['bold']),presentRoot_Lower_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Upper_Sum = presentRoot_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots Upper:', 'blue', attrs=['bold']),presentRoot_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialRoot_Lower_Sum = potentialRoot_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots Lower:', 'blue', attrs=['bold']),potentialRoot_Lower_Sum.getInfo())\n",
    "# potentialRoot_Upper_Sum = potentialRoot_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots Upper:', 'blue', attrs=['bold']),potentialRoot_Upper_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "presentTGB_Lower_Abs = presentAGB_Lower_Abs.multiply(rootShootRatioLower.add(1))\n",
    "presentTGB_Upper_Abs = presentAGB_Upper_Abs.multiply(rootShootRatioUpper.add(1))\n",
    "\n",
    "potentialTGB_Lower_Abs = potentialAGB_Lower_Abs.multiply(rootShootRatioLower.add(1))\n",
    "potentialTGB_Upper_Abs = potentialAGB_Upper_Abs.multiply(rootShootRatioUpper.add(1))\n",
    "\n",
    "# presentTGB_Lower_Sum = presentTGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB Lower:', 'blue', attrs=['bold']),presentTGB_Lower_Sum.getInfo())\n",
    "\n",
    "# presentTGB_Upper_Sum = presentTGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB Upper:', 'blue', attrs=['bold']),presentTGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialTGB_Lower_Sum = potentialTGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB Lower:', 'blue', attrs=['bold']),potentialTGB_Lower_Sum.getInfo())\n",
    "# potentialTGB_Upper_Sum = potentialTGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB Upper:', 'blue', attrs=['bold']),potentialTGB_Upper_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Calculate the Upper and Lower of present and potential Litter and PGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the dead wood and litter layer\n",
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "deadWoodLitterRatioLower = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Lower_Map\").unmask()\n",
    "deadWoodLitterRatioUpper = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Upper_Map\").unmask()\n",
    "\n",
    "# calculate the present and potential PGB\n",
    "presentPGB_Abs = presentTGB_Abs.multiply(deadWoodLitterRatio)\n",
    "potentialPGB_Abs = potentialTGB_Abs.multiply(deadWoodLitterRatio)\n",
    "\n",
    "# calculate the present and potential dead wood and litter\n",
    "presentLitter_Abs = presentTGB_Abs.multiply(deadWoodLitterRatio.subtract(1))\n",
    "potentialLitter_Abs = potentialTGB_Abs.multiply(deadWoodLitterRatio.subtract(1))\n",
    "\n",
    "# calculate the present Dead wood and litter\n",
    "presentLitter_Lower_Abs = presentTGB_Lower_Abs.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "presentLitter_Upper_Abs = presentTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "# calculate the potential dead wood and litter\n",
    "potentialLitter_Lower_Abs = potentialTGB_Lower_Abs.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "potentialLitter_Upper_Abs = potentialTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "# get the densities\n",
    "presentPGB_Lower = presentTGB_Lower.multiply(deadWoodLitterRatioLower)\n",
    "presentPGB_Upper = presentTGB_Upper.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "potentialPGB_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioLower)\n",
    "potentialPGB_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "presentLitter_Lower = presentTGB_Lower.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "presentLitter_Upper = presentTGB_Upper.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "potentialLitter_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "potentialLitter_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "# presentPGB_Abs_Sum = presentPGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB:', 'blue', attrs=['bold']),presentPGB_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Abs_Sum = potentialPGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB:', 'blue', attrs=['bold']),potentialPGB_Abs_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Abs_Sum = presentLitter_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter:', 'blue', attrs=['bold']),presentLitter_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Abs_Sum = potentialLitter_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter:', 'blue', attrs=['bold']),potentialLitter_Abs_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Lower_Sum = presentLitter_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter Lower:', 'blue', attrs=['bold']),presentLitter_Lower_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Upper_Sum = presentLitter_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter Upper:', 'blue', attrs=['bold']),presentLitter_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Lower_Sum = potentialLitter_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter Lower:', 'blue', attrs=['bold']),potentialLitter_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Upper_Sum = potentialLitter_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter Upper:', 'blue', attrs=['bold']),potentialLitter_Upper_Sum.getInfo())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the present PGB Lower and Upper\n",
    "presentPGB_Lower_Abs = presentTGB_Lower_Abs.multiply(deadWoodLitterRatioLower)\n",
    "presentPGB_Upper_Abs = presentTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper)\n",
    "# calculate the potential PGB Lower and Upper\n",
    "potentialPGB_Lower_Abs = potentialTGB_Lower_Abs.multiply(deadWoodLitterRatioLower)\n",
    "potentialPGB_Upper_Abs = potentialTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "# presentPGB_Lower_Sum = presentPGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB Lower:', 'blue', attrs=['bold']),presentPGB_Lower_Sum.getInfo())\n",
    "\n",
    "# presentPGB_Upper_Sum = presentPGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB Upper:', 'blue', attrs=['bold']),presentPGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Lower_Sum = potentialPGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB Lower:', 'blue', attrs=['bold']),potentialPGB_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Upper_Sum = potentialPGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB Upper:', 'blue', attrs=['bold']),potentialPGB_Upper_Sum.getInfo())\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 Export the upper and lower images to Assets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "SandermannCarbonDiff = ee.Image(\"users/leonidmoore/ForestBiomass/SoilOrganicCarbonModel/SOCS_0_200cm_Diff_1km_Present_subtract_NoLU\").unmask()\n",
    "SandermannCarbonPresent = ee.Image(\"users/leonidmoore/ForestBiomass/SoilOrganicCarbonModel/SOCS_0_200cm_1km_Present\").unmask()\n",
    "\n",
    "# mask the diffrence layer\n",
    "SandermannCarbonLoss = SandermannCarbonDiff.multiply(SandermannCarbonDiff.gt(0))\n",
    "\n",
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask = presentForestCover.gt(0)\n",
    "potentialMask = potentialCoverAdjusted.gte(0.1)\n",
    "\n",
    "# calculate the sum of the potential in soil with the consideration of forest cover\n",
    "SandermannCarbonStockLoss = SandermannCarbonLoss.multiply(pixelArea).divide(1000000000).mask(biomeMask).mask(potentialMask).multiply(potentialCoverAdjusted)\n",
    "\n",
    "# add the soil into the PGB as the total potential\n",
    "potentialTotal_Abs = potentialPGB_Abs.add(SandermannCarbonStockLoss)\n",
    "# compose those bands into an image\n",
    "lowerUpperImage = presentAGB_Lower_Abs.rename('preAGB_Lower').addBands(presentAGB_Upper_Abs.rename('preAGB_Upper')).addBands(potentialAGB_Lower_Abs.rename('potAGB_Lower')).addBands(potentialAGB_Upper_Abs.rename('potAGB_Upper')).addBands(presentRoot_Lower_Abs.rename('preRoot_Lower')).addBands(presentRoot_Upper_Abs.rename('preRoot_Upper')).addBands(potentialRoot_Lower_Abs.rename('potRoot_Lower')).addBands(potentialRoot_Upper_Abs.rename('potRoot_Upper')).addBands(presentLitter_Lower_Abs.rename('preLitter_Lower')).addBands(presentLitter_Upper_Abs.rename('preLitter_Upper')).addBands(potentialLitter_Lower_Abs.rename('potLitter_Lower')).addBands(potentialLitter_Upper_Abs.rename('potLitter_Upper')).addBands(potentialTotal_Abs.rename('PotentialTotal'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'state': 'READY',\n",
       " 'description': 'SD2_Upper_Lower_Uncertainty_maps_Export',\n",
       " 'creation_timestamp_ms': 1690807556161,\n",
       " 'update_timestamp_ms': 1690807556161,\n",
       " 'start_timestamp_ms': 0,\n",
       " 'task_type': 'EXPORT_IMAGE',\n",
       " 'id': 'OGK6QXUIHNQ7DC3XHS4AN7DB',\n",
       " 'name': 'projects/earthengine-legacy/operations/OGK6QXUIHNQ7DC3XHS4AN7DB'}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exportUpperLower = ee.batch.Export.image.toAsset(image = lowerUpperImage,\n",
    "                                               description = 'SD2_Upper_Lower_Uncertainty_maps_Export',\n",
    "                                               assetId = 'users/leonidmoore/ForestBiomass/UncertaintyFigure/SD2_Lower_Upper_Map',\n",
    "                                               region = unboundedGeo,\n",
    "                                               crs = 'EPSG:4326',\n",
    "                                               crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                               maxPixels = 1e13)\n",
    "# start the export task\n",
    "exportUpperLower.start()\n",
    "# show the task status\n",
    "exportUpperLower.status()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 Calculate the Abs for different parts at biome level"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>PresentAGB</th>\n",
       "      <th>PotentialAGB</th>\n",
       "      <th>PresentRoot</th>\n",
       "      <th>PotentialRoot</th>\n",
       "      <th>PresentTGB</th>\n",
       "      <th>PotentialTGB</th>\n",
       "      <th>PresentLitter</th>\n",
       "      <th>PotentialLitter</th>\n",
       "      <th>PresentPGB</th>\n",
       "      <th>PotentialPGB</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>146.5</td>\n",
       "      <td>195.0</td>\n",
       "      <td>40.0</td>\n",
       "      <td>52.0</td>\n",
       "      <td>186.5</td>\n",
       "      <td>246.9</td>\n",
       "      <td>41.0</td>\n",
       "      <td>54.3</td>\n",
       "      <td>227.5</td>\n",
       "      <td>301.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5.1</td>\n",
       "      <td>13.1</td>\n",
       "      <td>1.4</td>\n",
       "      <td>3.4</td>\n",
       "      <td>6.5</td>\n",
       "      <td>16.5</td>\n",
       "      <td>1.4</td>\n",
       "      <td>3.6</td>\n",
       "      <td>7.9</td>\n",
       "      <td>20.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2.0</td>\n",
       "      <td>3.7</td>\n",
       "      <td>0.5</td>\n",
       "      <td>0.9</td>\n",
       "      <td>2.5</td>\n",
       "      <td>4.6</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.0</td>\n",
       "      <td>3.1</td>\n",
       "      <td>5.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>36.0</td>\n",
       "      <td>59.1</td>\n",
       "      <td>9.3</td>\n",
       "      <td>15.1</td>\n",
       "      <td>45.2</td>\n",
       "      <td>74.2</td>\n",
       "      <td>14.9</td>\n",
       "      <td>24.5</td>\n",
       "      <td>60.1</td>\n",
       "      <td>98.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>18.6</td>\n",
       "      <td>23.4</td>\n",
       "      <td>5.0</td>\n",
       "      <td>6.2</td>\n",
       "      <td>23.6</td>\n",
       "      <td>29.6</td>\n",
       "      <td>7.8</td>\n",
       "      <td>9.8</td>\n",
       "      <td>31.3</td>\n",
       "      <td>39.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>45.5</td>\n",
       "      <td>58.2</td>\n",
       "      <td>12.2</td>\n",
       "      <td>15.7</td>\n",
       "      <td>57.7</td>\n",
       "      <td>73.9</td>\n",
       "      <td>46.2</td>\n",
       "      <td>59.0</td>\n",
       "      <td>103.9</td>\n",
       "      <td>132.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>29.8</td>\n",
       "      <td>76.3</td>\n",
       "      <td>8.9</td>\n",
       "      <td>23.0</td>\n",
       "      <td>38.7</td>\n",
       "      <td>99.3</td>\n",
       "      <td>8.5</td>\n",
       "      <td>21.9</td>\n",
       "      <td>47.3</td>\n",
       "      <td>121.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>4.2</td>\n",
       "      <td>20.1</td>\n",
       "      <td>1.2</td>\n",
       "      <td>5.8</td>\n",
       "      <td>5.4</td>\n",
       "      <td>26.0</td>\n",
       "      <td>1.8</td>\n",
       "      <td>8.6</td>\n",
       "      <td>7.2</td>\n",
       "      <td>34.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.1</td>\n",
       "      <td>2.9</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.9</td>\n",
       "      <td>1.5</td>\n",
       "      <td>3.8</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.8</td>\n",
       "      <td>1.8</td>\n",
       "      <td>4.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2.3</td>\n",
       "      <td>9.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>2.4</td>\n",
       "      <td>3.0</td>\n",
       "      <td>11.4</td>\n",
       "      <td>1.0</td>\n",
       "      <td>3.7</td>\n",
       "      <td>3.9</td>\n",
       "      <td>15.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>4.1</td>\n",
       "      <td>10.7</td>\n",
       "      <td>1.2</td>\n",
       "      <td>3.2</td>\n",
       "      <td>5.3</td>\n",
       "      <td>13.9</td>\n",
       "      <td>4.2</td>\n",
       "      <td>11.1</td>\n",
       "      <td>9.5</td>\n",
       "      <td>24.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>2.2</td>\n",
       "      <td>7.8</td>\n",
       "      <td>0.6</td>\n",
       "      <td>2.4</td>\n",
       "      <td>2.8</td>\n",
       "      <td>10.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>2.1</td>\n",
       "      <td>3.4</td>\n",
       "      <td>12.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>1.4</td>\n",
       "      <td>25.7</td>\n",
       "      <td>0.4</td>\n",
       "      <td>6.4</td>\n",
       "      <td>1.8</td>\n",
       "      <td>32.1</td>\n",
       "      <td>0.4</td>\n",
       "      <td>6.8</td>\n",
       "      <td>2.2</td>\n",
       "      <td>38.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.1</td>\n",
       "      <td>2.1</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.3</td>\n",
       "      <td>2.5</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.6</td>\n",
       "      <td>3.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>299.9</td>\n",
       "      <td>507.2</td>\n",
       "      <td>81.8</td>\n",
       "      <td>137.8</td>\n",
       "      <td>381.8</td>\n",
       "      <td>644.8</td>\n",
       "      <td>129.0</td>\n",
       "      <td>207.8</td>\n",
       "      <td>510.7</td>\n",
       "      <td>852.7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     PresentAGB  PotentialAGB  PresentRoot  PotentialRoot  PresentTGB  \\\n",
       "0         146.5         195.0         40.0           52.0       186.5   \n",
       "1           5.1          13.1          1.4            3.4         6.5   \n",
       "2           2.0           3.7          0.5            0.9         2.5   \n",
       "3          36.0          59.1          9.3           15.1        45.2   \n",
       "4          18.6          23.4          5.0            6.2        23.6   \n",
       "5          45.5          58.2         12.2           15.7        57.7   \n",
       "6          29.8          76.3          8.9           23.0        38.7   \n",
       "7           4.2          20.1          1.2            5.8         5.4   \n",
       "8           1.1           2.9          0.3            0.9         1.5   \n",
       "9           2.3           9.1          0.6            2.4         3.0   \n",
       "10          4.1          10.7          1.2            3.2         5.3   \n",
       "11          2.2           7.8          0.6            2.4         2.8   \n",
       "12          1.4          25.7          0.4            6.4         1.8   \n",
       "13          1.1           2.1          0.2            0.4         1.3   \n",
       "sum       299.9         507.2         81.8          137.8       381.8   \n",
       "\n",
       "     PotentialTGB  PresentLitter  PotentialLitter  PresentPGB  PotentialPGB  \n",
       "0           246.9           41.0             54.3       227.5         301.3  \n",
       "1            16.5            1.4              3.6         7.9          20.1  \n",
       "2             4.6            0.6              1.0         3.1           5.6  \n",
       "3            74.2           14.9             24.5        60.1          98.7  \n",
       "4            29.6            7.8              9.8        31.3          39.4  \n",
       "5            73.9           46.2             59.0       103.9         132.9  \n",
       "6            99.3            8.5             21.9        47.3         121.2  \n",
       "7            26.0            1.8              8.6         7.2          34.5  \n",
       "8             3.8            0.3              0.8         1.8           4.6  \n",
       "9            11.4            1.0              3.7         3.9          15.2  \n",
       "10           13.9            4.2             11.1         9.5          24.9  \n",
       "11           10.1            0.6              2.1         3.4          12.3  \n",
       "12           32.1            0.4              6.8         2.2          38.9  \n",
       "13            2.5            0.3              0.6         1.6           3.1  \n",
       "sum         644.8          129.0            207.8       510.7         852.7  "
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absImage = presentAGB_Abs.rename('PresentAGB').addBands(potentialAGB_Abs.rename('PotentialAGB')).addBands(presentRoot_Abs.rename('PresentRoot')).addBands(potentialRoot_Abs.rename('PotentialRoot')).addBands(presentTGB_Abs.rename('PresentTGB')).addBands(potentialTGB_Abs.rename('PotentialTGB')).addBands(presentLitter_Abs.rename('PresentLitter')).addBands(potentialLitter_Abs.rename('PotentialLitter')).addBands(presentPGB_Abs.rename('PresentPGB')).addBands(potentialPGB_Abs.rename('PotentialPGB'))\n",
    "\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    perBiomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absImage.mask(perBiomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['PresentAGB','PotentialAGB','PresentRoot','PotentialRoot','PresentTGB','PotentialTGB','PresentLitter','PotentialLitter','PresentPGB','PotentialPGB']).round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/SD2_Abs_for_diff_parts_at_Biome_Level.csv',header=True,mode='w+')\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7 Calculate the Abs for different parts at biome level"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>preAGB_Lower</th>\n",
       "      <th>preAGB_Upper</th>\n",
       "      <th>potAGB_Lower</th>\n",
       "      <th>potAGB_Upper</th>\n",
       "      <th>preRoot_Lower</th>\n",
       "      <th>preRoot_Upper</th>\n",
       "      <th>potRoot_Lower</th>\n",
       "      <th>potRoot_Upper</th>\n",
       "      <th>preLitter_Lower</th>\n",
       "      <th>preLitter_Upper</th>\n",
       "      <th>potLitter_Lower</th>\n",
       "      <th>potLitter_Upper</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>105.2</td>\n",
       "      <td>188.1</td>\n",
       "      <td>175.7</td>\n",
       "      <td>209.8</td>\n",
       "      <td>22.5</td>\n",
       "      <td>62.8</td>\n",
       "      <td>37.0</td>\n",
       "      <td>68.0</td>\n",
       "      <td>19.2</td>\n",
       "      <td>75.3</td>\n",
       "      <td>31.9</td>\n",
       "      <td>83.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3.6</td>\n",
       "      <td>6.8</td>\n",
       "      <td>11.3</td>\n",
       "      <td>14.8</td>\n",
       "      <td>0.8</td>\n",
       "      <td>2.1</td>\n",
       "      <td>2.4</td>\n",
       "      <td>4.5</td>\n",
       "      <td>0.7</td>\n",
       "      <td>2.7</td>\n",
       "      <td>2.0</td>\n",
       "      <td>5.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1.5</td>\n",
       "      <td>2.6</td>\n",
       "      <td>3.2</td>\n",
       "      <td>4.1</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.7</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1.2</td>\n",
       "      <td>0.3</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>24.4</td>\n",
       "      <td>48.1</td>\n",
       "      <td>51.0</td>\n",
       "      <td>64.5</td>\n",
       "      <td>5.6</td>\n",
       "      <td>14.0</td>\n",
       "      <td>11.5</td>\n",
       "      <td>18.6</td>\n",
       "      <td>9.0</td>\n",
       "      <td>23.0</td>\n",
       "      <td>18.7</td>\n",
       "      <td>30.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>13.0</td>\n",
       "      <td>24.3</td>\n",
       "      <td>18.7</td>\n",
       "      <td>24.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>7.4</td>\n",
       "      <td>4.4</td>\n",
       "      <td>7.3</td>\n",
       "      <td>4.8</td>\n",
       "      <td>11.7</td>\n",
       "      <td>6.9</td>\n",
       "      <td>11.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>32.6</td>\n",
       "      <td>58.6</td>\n",
       "      <td>49.3</td>\n",
       "      <td>61.4</td>\n",
       "      <td>8.0</td>\n",
       "      <td>17.5</td>\n",
       "      <td>12.2</td>\n",
       "      <td>18.4</td>\n",
       "      <td>27.5</td>\n",
       "      <td>71.4</td>\n",
       "      <td>41.7</td>\n",
       "      <td>75.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>20.5</td>\n",
       "      <td>39.7</td>\n",
       "      <td>63.5</td>\n",
       "      <td>88.4</td>\n",
       "      <td>5.2</td>\n",
       "      <td>13.7</td>\n",
       "      <td>16.3</td>\n",
       "      <td>31.0</td>\n",
       "      <td>3.9</td>\n",
       "      <td>16.0</td>\n",
       "      <td>12.0</td>\n",
       "      <td>35.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>3.1</td>\n",
       "      <td>5.5</td>\n",
       "      <td>16.9</td>\n",
       "      <td>23.0</td>\n",
       "      <td>0.8</td>\n",
       "      <td>1.8</td>\n",
       "      <td>4.3</td>\n",
       "      <td>7.8</td>\n",
       "      <td>1.2</td>\n",
       "      <td>2.7</td>\n",
       "      <td>6.4</td>\n",
       "      <td>11.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.9</td>\n",
       "      <td>1.4</td>\n",
       "      <td>2.5</td>\n",
       "      <td>3.4</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.5</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.2</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.6</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>1.6</td>\n",
       "      <td>3.1</td>\n",
       "      <td>7.4</td>\n",
       "      <td>10.6</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.0</td>\n",
       "      <td>1.7</td>\n",
       "      <td>3.2</td>\n",
       "      <td>0.6</td>\n",
       "      <td>1.5</td>\n",
       "      <td>2.7</td>\n",
       "      <td>5.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>2.6</td>\n",
       "      <td>5.8</td>\n",
       "      <td>8.7</td>\n",
       "      <td>12.3</td>\n",
       "      <td>0.7</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.2</td>\n",
       "      <td>4.5</td>\n",
       "      <td>2.2</td>\n",
       "      <td>7.4</td>\n",
       "      <td>7.5</td>\n",
       "      <td>15.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>1.4</td>\n",
       "      <td>3.0</td>\n",
       "      <td>6.3</td>\n",
       "      <td>9.0</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.2</td>\n",
       "      <td>1.7</td>\n",
       "      <td>3.6</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.7</td>\n",
       "      <td>0.2</td>\n",
       "      <td>5.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>0.9</td>\n",
       "      <td>2.0</td>\n",
       "      <td>20.8</td>\n",
       "      <td>30.8</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.7</td>\n",
       "      <td>4.5</td>\n",
       "      <td>9.4</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.1</td>\n",
       "      <td>0.5</td>\n",
       "      <td>16.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>0.8</td>\n",
       "      <td>1.4</td>\n",
       "      <td>1.7</td>\n",
       "      <td>2.3</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.4</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.7</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.5</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>212.1</td>\n",
       "      <td>390.4</td>\n",
       "      <td>437.0</td>\n",
       "      <td>558.4</td>\n",
       "      <td>48.3</td>\n",
       "      <td>125.8</td>\n",
       "      <td>99.8</td>\n",
       "      <td>179.4</td>\n",
       "      <td>69.7</td>\n",
       "      <td>216.6</td>\n",
       "      <td>131.9</td>\n",
       "      <td>299.7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     preAGB_Lower  preAGB_Upper  potAGB_Lower  potAGB_Upper  preRoot_Lower  \\\n",
       "0           105.2         188.1         175.7         209.8           22.5   \n",
       "1             3.6           6.8          11.3          14.8            0.8   \n",
       "2             1.5           2.6           3.2           4.1            0.3   \n",
       "3            24.4          48.1          51.0          64.5            5.6   \n",
       "4            13.0          24.3          18.7          24.0            3.0   \n",
       "5            32.6          58.6          49.3          61.4            8.0   \n",
       "6            20.5          39.7          63.5          88.4            5.2   \n",
       "7             3.1           5.5          16.9          23.0            0.8   \n",
       "8             0.9           1.4           2.5           3.4            0.2   \n",
       "9             1.6           3.1           7.4          10.6            0.4   \n",
       "10            2.6           5.8           8.7          12.3            0.7   \n",
       "11            1.4           3.0           6.3           9.0            0.4   \n",
       "12            0.9           2.0          20.8          30.8            0.2   \n",
       "13            0.8           1.4           1.7           2.3            0.2   \n",
       "sum         212.1         390.4         437.0         558.4           48.3   \n",
       "\n",
       "     preRoot_Upper  potRoot_Lower  potRoot_Upper  preLitter_Lower  \\\n",
       "0             62.8           37.0           68.0             19.2   \n",
       "1              2.1            2.4            4.5              0.7   \n",
       "2              0.7            0.7            1.2              0.3   \n",
       "3             14.0           11.5           18.6              9.0   \n",
       "4              7.4            4.4            7.3              4.8   \n",
       "5             17.5           12.2           18.4             27.5   \n",
       "6             13.7           16.3           31.0              3.9   \n",
       "7              1.8            4.3            7.8              1.2   \n",
       "8              0.5            0.6            1.2              0.2   \n",
       "9              1.0            1.7            3.2              0.6   \n",
       "10             2.0            2.2            4.5              2.2   \n",
       "11             1.2            1.7            3.6              0.0   \n",
       "12             0.7            4.5            9.4              0.0   \n",
       "13             0.4            0.3            0.7              0.1   \n",
       "sum          125.8           99.8          179.4             69.7   \n",
       "\n",
       "     preLitter_Upper  potLitter_Lower  potLitter_Upper  \n",
       "0               75.3             31.9             83.4  \n",
       "1                2.7              2.0              5.8  \n",
       "2                1.0              0.6              1.6  \n",
       "3               23.0             18.7             30.8  \n",
       "4               11.7              6.9             11.6  \n",
       "5               71.4             41.7             75.0  \n",
       "6               16.0             12.0             35.8  \n",
       "7                2.7              6.4             11.4  \n",
       "8                0.6              0.5              1.4  \n",
       "9                1.5              2.7              5.1  \n",
       "10               7.4              7.5             15.8  \n",
       "11               1.7              0.2              5.0  \n",
       "12               1.1              0.5             16.1  \n",
       "13               0.5              0.3              0.9  \n",
       "sum            216.6            131.9            299.7  "
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = presentAGB_Lower_Abs.rename('preAGB_Lower').addBands(presentAGB_Upper_Abs.rename('preAGB_Upper')).addBands(potentialAGB_Lower_Abs.rename('potAGB_Lower')).addBands(potentialAGB_Upper_Abs.rename('potAGB_Upper')).addBands(presentRoot_Lower_Abs.rename('preRoot_Lower')).addBands(presentRoot_Upper_Abs.rename('preRoot_Upper')).addBands(potentialRoot_Lower_Abs.rename('potRoot_Lower')).addBands(potentialRoot_Upper_Abs.rename('potRoot_Upper')).addBands(presentLitter_Lower_Abs.rename('preLitter_Lower')).addBands(presentLitter_Upper_Abs.rename('preLitter_Upper')).addBands(potentialLitter_Lower_Abs.rename('potLitter_Lower')).addBands(potentialLitter_Upper_Abs.rename('potLitter_Upper'))\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    perBiomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(perBiomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['preAGB_Lower','preAGB_Upper','potAGB_Lower','potAGB_Upper','preRoot_Lower','preRoot_Upper','potRoot_Lower','potRoot_Upper','preLitter_Lower','preLitter_Upper','potLitter_Lower','potLitter_Upper']).round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/SD2_Uncertainty_for_diff_parts_at_Biome_Level.csv',header=True,mode='w+')\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
